#include <bits/stdc++.h>

using namespace std;

class DSU {
public:
    vector<int> parent;
    DSU(int n) {
        parent.resize(n);
        iota(parent.begin(), parent.end(), 0);
    }

    int find(int x) {
        if (parent[x] != x) {
            parent[x] = find(parent[x]);
        }
        return parent[x];
    }

    void unite(int x, int y) {
        int rootX = find(x);
        int rootY = find(y);
        if (rootX != rootY) {
            parent[rootX] = rootY;
        }
    }
};

class Solution {
public:
    int sortPermutation(vector<int>& nums) {
        int n = nums.size();
        int ans = 0;
        
        for (int i = 30; i >= 0; --i) {
            int mask = ans | (1 << i);
            
            DSU dsu(n);
            
            for (int j = 0; j < n; ++j) {
                if ((j & mask) == mask) {
                    dsu.unite(j, mask);
                }
            }
            
            bool canSort = true;
            for (int j = 0; j < n; ++j) {
                if (dsu.find(j) != dsu.find(nums[j])) {
                    canSort = false;
                    break;
                }
            }
            
            if (canSort) {
                ans = mask;
            }
        }
        
        return ans;
    }
};
